/**
 * Created by Amy on 2018/8/7.
 */

$(function () {
  isLoginFun();
  header();
  $("#ctl01_lblUserName").text(getCookie('userName'));
  getProjectInfo();
  getQuestionnaireInfo();
  var projectName = getCookie('projectName');
  var oTable = new AddQuestionnaireTableInit();
  oTable.Init();
});

//回车事件
$(document).keydown(function (event) {
  if (event.keyCode == 13) {
    getQuestionnaireInfo();
  }
});

$('#questionnairebtn').on("keydown", function (event) {
  var keyCode = event.keyCode || event.which;
  if (keyCode == "13") {
    event.preventDefault();
  }
});

// 查看项目详细信息
function getProjectInfo() {
  var projectName = getCookie('projectName');
  var url = '/queryProjectList';
  var data = {
    "projectName": projectName
  };
  commonAjaxPost(true, url, data, function (result) {
    //console.log(result)
    getProjectInfoSuccess(result)
  });

}

// 查看项目详细信息成功
function getProjectInfoSuccess(result) {
  //console.log(result)
  if (result.code == "666") {
    var projectInfo = result.data[0];
    $("#projectNameSpan").text(projectInfo.project_name);
    $("#createTimeSpan").text(
        projectInfo.creation_date.replace(/-/g, '/').replace(/T/g, ' '));
    $("#adminSpan").text(projectInfo.created_by);
    $("#projectContentSpan").text(projectInfo.project_content);

  } else if (result.code == "333") {
    layer.msg(result.message, {icon: 2});
    setTimeout(function () {
      window.location.href = 'login.html';
    }, 1000)
  } else {
    layer.msg(result.message, {icon: 2})
  }
}

function getQuestionnaireInfo(result) {
  var projectName = getCookie('projectName');
  var queryquestionnairename = $("#keyWord").val();
  // var url = '/queryQuestionnaireListByProjectId';
  var data = {
    "projectName": projectName,
    'questionName': queryquestionnairename
  };
  debugger;
  commonAjaxPost(true, '/queryQuestionnaireListByProjectId', data,
      function (result) {
        if (result.code == "666") {
          $("#questTableBody").empty();
          var data = result.data;
          console.log(data)
          if (data.length) {
            var text = "";
            var i = 0;
            for (; i < data.length; i++) {
              var questionnaireData = data[i];
              var starttime=questionnaireData.startTime;
              var endtime=questionnaireData.endTime;
              if(starttime!='undefined'){
                starttime=starttime.replace(/-/g,'/').replace(/T/g,' ');
              }
              if(endtime!='undefined'){
                endtime=endtime.replace(/-/g,'/').replace(/T/g,' ');
              }
              //调查类型
              var dataid = questionnaireData.dataId;
              var type = '';
              // 在校生：2；毕业生：3；教师：4；用人单位：5
              if (dataid == 2) {
                type = '在校生';
              }
              if (dataid == 3) {
                type = '毕业生';
              }
              if (dataid == 4) {
                type = '教师';
              }
              if (dataid == 5) {
                type = '用人单位';
              }
              //问卷状态
              var status = questionnaireData.questionStop;
              var statusText = '';
              if (status == "0") {
                statusText = "已过期";
              } else if (status == "1") {
                statusText = "发布进行中";
              } else if (status == "2") {
                statusText = "暂停发布中";
              } else if (status == "3") {
                statusText = "问卷关闭中";
              } else if (status == "4") {
                statusText = "历史问卷";
              } else if (status == "5") {
                statusText = "未发布";
              }
              text += "<tr>";
              text += "<td>" + (i + 1) + "</td>";
              text += "<td>" + questionnaireData.questionName + "</td>";
              text += "<td>" + type + "</td>";
              text += "<td>" + statusText + "</td>";
              text += "<td>" + starttime + "</td>";
              text += "<td>" + endtime + "</td>";
              text += "<td><button type=\"button\" id=\"btnEdit" + i
                  + "\"onclick=\"editQuestion("
                  + "'" + questionnaireData.id + "'" + "," + "'"
                  + questionnaireData.questionName + "'" + "," + "'"
                  + questionnaireData.questionContent + "'" + "," + "'"
                  + questionnaireData.endTime + "'" + "," + "'"
                  + questionnaireData.startTime + "'" + "," + "'"
                  + questionnaireData.dataId + "'"
                  + ")\" class=\"btn btn-default-g ajax-link\">编辑</button>&nbsp;&nbsp;";
              text += "<button type=\"button\" id=\"btn_look1\" onclick=\"cancelConnection("
                  + "'" + questionnaireData.id + "'" + "," + "'" + name + "'"
                  + ")\" class=\"btn btn-danger-g ajax-link\">取消关联</button>&nbsp;&nbsp;";
              text += "</tr>";
            }
            $("#questTableBody").append(text);
          } else {
            $("#questTableBody").empty();
            var text = "<tr><td colspan='5'>暂无问卷或问卷已过期</td></tr>";
            $("#questTableBody").append(text);
          }
        }
      });
}

//编辑问卷
function editQuestion(id, name, content, endTime, startTime, dataId) {
  console.log(startTime)
  var data = {
    "id": id
  };
  commonAjaxPost(true, '/selectQuestionnaireStatus', data, function (result) {
    //console.log(result);
    //5：问卷未发布 1：问卷进行中
    if (result.code == "666") {
      if (result.data == "3") {
        deleteCookie("questionId");
        deleteCookie("questionName");
        deleteCookie("questionContent");
        deleteCookie("endTime");
        deleteCookie("startTime");
        setCookie("questionId", id);
        setCookie("questionName", name);
        setCookie("questionContent", content);
        setCookie("endTime", endTime);
        setCookie("startTime", startTime);
        setCookie("dataId", dataId);
        //console.log(getCookie("questionId"))
        window.location.href = 'editQuestionnaire.html'
      } else {
        layer.msg("问卷发布过或正在发布，不能编辑", {icon: 2});
      }
    }
    /*
    if (result.code == "666") {
        if (result.data == "1") {
            if ($("#operationAll" + m + n).children("a:first-child").text() == '开启') {
                //judgeIfChangeStatus(m, n);
            }
            layer.msg('问卷运行中，不可修改', {icon: 2});
        } else if (result.data != "1") {
           // commonAjaxPost(true, '/selectQuestSendStatus', {id: id}, function (result) {
                //发送过问卷
            //    if (result.code == "40003") {
             //       setCookie("ifEditQuestType", "false");
             //   } else if (result.code == "666") {         //未发送过问卷
             //       setCookie("ifEditQuestType", "true");
             //   }
          //  });
            deleteCookie("questionId");
            deleteCookie("questionName");
            deleteCookie("questionContent");
            deleteCookie("endTime");
            setCookie("questionId", id);
            setCookie("questionName", name);
            setCookie("questionContent", content);
            setCookie("endTime", endTime);
            setCookie("creationDate", creationDate);
            setCookie("dataId", dataId);
            //window.location.href = 'editQuestionnaire.html'
        }
    } else if (result.code == "333") {
        layer.msg(result.message, {icon: 2});
        setTimeout(function () {
            window.location.href = 'login.html';
        }, 1000)
    } else {
        layer.msg(result.message, {icon: 2})
    }*/
  });
}

//取消问卷关联
function cancelConnection(id, name) {
  layer.confirm('您确认要取消与项目的关联吗？', {
    btn: ['确定', '取消'] //按钮
  }, function () {
    // console.log(id)
    var data = {
      "id": id
    }
    commonAjaxPost(true, '/cancelQuestionnaireProject', data,
        function (result) {
          // console.log(result);
          //5：问卷未发布 1：问卷进行中
          if (result.code == "666") {
            layer.msg(result.message, {icon: 1});
            //刷新表单
            getQuestionnaireInfo();
            //刷新添加问卷表格
            getAddQuestionnaireList();
          } else if (result.code == "20001") {
            layer.msg(result.message, {icon: 2});
          } else {
            layer.msg(result.message, {icon: 2});
          }
        });
  }, function () {
  });
}

function getAddQuestionnaireList() {
  $("#questionnaireAddTable").bootstrapTable('refresh');
}

function AddQuestionnaireTableInit() {

  var oTableInit = new Object();
  //初始化Table
  oTableInit.Init = function () {
    $('#questionnaireAddTable').bootstrapTable({
      url: httpRequestUrl + '/queryQuestionnaireByNameAndProjectId',         //请求后台的URL（*）
      method: 'POST',                      //请求方式（*）
      striped: true,                      //是否显示行间隔色
      cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
      pagination: true,                   //是否显示分页（*）
      sortOrder: "asc",                   //排序方式
      sortStable: true,                   //是否排序
      queryParamsType: '',
      dataType: 'json',
      paginationShowPageGo: true,
      showJumpto: true,
      pageNumber: 1, //初始化加载第一页，默认第一页
      queryParams: queryParams,//请求服务器时所传的参数
      sidePagination: 'server',//指定服务器端分页
      pageSize: 10,//单页记录数
      pageList: [10, 20, 30, 40],//分页步进值
      search: false, //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
      silent: true,
      showRefresh: true,                  //是否显示刷新按钮
      showToggle: false,
      minimumCountColumns: 2,             //最少允许的列数
      uniqueId: "id",                     //每一行的唯一标识，一般为主键列
      // curpage: typeof getCurPage() == "undefined" ? 1 : getCurPage(),

      columns: [{
        checkbox: true,
        visible: false
      }, {
        field: 'id',
        title: '序号',
        align: 'center',
        formatter: function (value, row, index) {
          return index + 1;
        }
      }, {
        field: 'questionnaireName',
        title: '问卷名称',
        align: 'center',
        //width: '230px'
      }, {
        field: 'questionnaireStatus',
        title: '问卷状态',
        align: 'center'
      }, {
        field: 'startTime',
        title: '开始时间',
        align: 'center'
      }, {
        field: 'endTime',
        title: '结束时间',
        align: 'center'
      }, {
        field: 'operation',
        title: '操作',
        align: 'center',
        events: operateEvents,//给按钮注册事件
        formatter: addFunctionAlty//表格中增加按钮
      }],
      responseHandler: function (res) {
        //console.log(res);
        // console.log(this.curpage);
        ///
        if (res.code == "666") {
          //var questionnaireinfo = res.data.list;
          //var questionnaireinfo=JSON.parse('[{"password":"1","startTime":"2022-05-12T10:09:28","id":"1","endTime":"2022-05-12T10:09:30","username":"aa","status":"1"},{"password":"123","startTime":"2022-05-12T12:10:37","id":"290e08f3ea154e33ad56a18171642db1","endTime":"2022-06-11T12:10:37","username":"aaa","status":"1"},{"password":"1","startTime":"2018-10-24T09:49:00","id":"8ceeee2995f3459ba1955f85245dc7a5","endTime":"2025-11-24T09:49:00","username":"admin","status":"1"},{"password":"aa","startTime":"2022-05-16T12:01:54","id":"a6f15c3be07f42e5965bec199f7ebbe6","endTime":"2022-06-15T12:01:54","username":"aaaaa","status":"1"}]');
          // console.log(res.data);
          var jstr = JSON.stringify(res.data.list);
          var questionnaireinfo = JSON.parse(jstr);
          var NewData = [];
          if (questionnaireinfo.length) {
            for (var i = 0; i < questionnaireinfo.length; i++) {
              var dataNewObj = {
                'id': '',
                "questionnaireName": '',
                'questionnaireStatus': '',
                "startTime": '',
                'endTime': '',
              };
              var status2 = questionnaireinfo[i].question_stop;
              var statusText = "";
              if (status2 == "0") {
                statusText = "已过期";
              } else if (status2 == "1") {
                statusText = "发布进行中";
              } else if (status2 == "2") {
                statusText = "暂停发布中";
              } else if (status2 == "3") {
                statusText = "问卷关闭中";
              } else if (status2 == "4") {
                statusText = "历史问卷";
              } else if (status2 == "5") {
                statusText = "未发布";
              }
              dataNewObj.id = questionnaireinfo[i].id;
              dataNewObj.questionnaireName = questionnaireinfo[i].question_name;
              dataNewObj.questionnaireStatus = statusText;
              dataNewObj.startTime = questionnaireinfo[i].start_time.replace(
                  /T/g, ' ');
              dataNewObj.endTime = questionnaireinfo[i].end_time.replace(/T/g,
                  ' ');
              NewData.push(dataNewObj);
            }
          }
          var data = {
            total: res.data.total,
            rows: NewData
          };
          return data;
        } else {
          var NewData = [];
          var data = {
            total: 0,
            rows: NewData
          };
          return data;
        }

      }

    });
  };

  // 得到查询的参数
  function queryParams(params) {
    var questionnairename = $("#questionnairename2").val();
    //console.log(questionnairename);
    var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
      ///
      pageNum: params.pageNumber,
      pageSize: params.pageSize,
      questionName: questionnairename,
      projectId: getCookie("projectId"),
    };
    return JSON.stringify(temp);
  }

  return oTableInit;
}

window.operateEvents = {
  //编辑
  'click #btn_count': function (e, value, row, index) {
    id = row.id;
    $.cookie('questionId', id);
  }
};

// 表格中按钮
function addFunctionAlty(value, row, index) {
  var btnText = "";
  //if (row.questionnaireStatus == "1") {
  btnText += "<button type=\"button\"  id=\"btn_add" + row.id
      + "\" onclick=\"addQuestionnaire(" + "'" + row.id + "'"
      + ")\" class=\"btn btn-default-g ajax-link\">添加</button>&nbsp;&nbsp;";
  //}
  return btnText;
}

// 添加问卷关联
function addQuestionnaire(id) {
  deleteCookie('questionId');
  var projectId = getCookie("projectId");
  //添加问卷到项目中
  var data = {
    "id": id,
    "projectId": projectId
  }
  var url = "/addQuestionnaireProject";
  commonAjaxPost(false, url, data, function (result) {
    if (result.code == "666") {
      layer.msg(result.message, {icon: 1})
      //添加按钮变为取消添加按钮
      $("#btn_add" + id).attr("disabled", "disabled");
      //刷新表单
      getQuestionnaireInfo();
      //刷新添加问卷表格
      getAddQuestionnaireList();
    } else {
      alert("添加失败");
    }
  });
}

//点击添加问卷按钮
function addConnectionList() {
  //显示添加问卷表格
  $("#ctl01_ContentPlaceHolder1_divInfo3").show();
  //addQuestionnaireBox2
  $("#addQuestionnaireBox2").show();
//添加问卷按钮不可用
  $("#btn_add_connection").attr("disabled", "disabled");
  //显示取消添加按钮可用
  $("#btn_hide_connection").removeAttr("disabled");
  //成功提示
  layer.msg("已在底部显示添加问卷表单", {icon: 1});
}

//点击隐藏添加按钮
function hideaddConnectionList() {
  //显示添加问卷表格
  $("#ctl01_ContentPlaceHolder1_divInfo3").hide();
  //addQuestionnaireBox2
  $("#addQuestionnaireBox2").hide();
//隐藏自身
  $("#btn_hide_connection").attr("disabled", "disabled");
  //显示添加问卷按钮
  $("#btn_add_connection").removeAttr("disabled");
  //成功提示
  layer.msg("已隐藏添加问卷表单", {icon: 1});
}